const express = require('express');
const cors = require('cors');
const path = require('path');

const app = express();
const PORT = 3000;

// 中间件
app.use(cors());
app.use(express.static('public'));
app.use(express.json());

// 存储所有连接的客户端
let clients = [];

// SSE端点
app.get('/events', (req, res) => {
    // 设置SSE响应头
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Cache-Control'
    });

    // 创建客户端对象
    const clientId = Date.now();
    const newClient = {
        id: clientId,  // 客户端ID
        response: res
    };

    // 添加到客户端列表
    clients.push(newClient);
    console.log(`客户端 ${clientId} 已连接，当前连接数: ${clients.length}`);

    // 发送欢迎消息
    res.write(`data: ${JSON.stringify({
        type: 'welcome',
        message: '连接成功！',
        clientId: clientId,
        timestamp: new Date().toISOString()
    })}\n\n`);

    // 处理客户端断开连接
    req.on('close', () => {
        clients = clients.filter(client => client.id !== clientId);
        console.log(`客户端 ${clientId} 已断开连接，当前连接数: ${clients.length}`);
    });
});

// 广播消息给所有客户端
function broadcastMessage(data) {
    const message = `data: ${JSON.stringify(data)}\n\n`;
    clients.forEach(client => {  //对每个客户端发送消息
        try {
            client.response.write(message);
        } catch (error) {
            console.error('发送消息失败:', error);
        }
    });
}

// 发送消息的API端点
app.post('/send-message', (req, res) => {
    const { message } = req.body;  // 从请求体中获取消息内容
    
    if (!message) {
        return res.status(400).json({ error: '消息内容不能为空' });
    }

    const data = {
        type: 'message',
        message: message,
        timestamp: new Date().toISOString(),
        sender: 'server'
    };

    broadcastMessage(data);
    res.json({ success: true, message: '消息已发送' });
});

// 定时发送心跳消息
setInterval(() => {
    const heartbeat = {
        type: 'heartbeat',
        message: '心跳检测',
        timestamp: new Date().toISOString(),
        activeClients: clients.length
    };
    broadcastMessage(heartbeat);
}, 30000); // 每30秒发送一次

// 定时发送随机数据
setInterval(() => {
    const randomData = {
        type: 'data',
        message: `随机数据: ${Math.floor(Math.random() * 1000)}`,
        value: Math.random(),
        timestamp: new Date().toISOString()
    };
    broadcastMessage(randomData);  //广播
}, 5000); // 每5秒发送一次

// 主页路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    console.log('SSE端点: http://localhost:3000/events');
});